package liuyuyang.utils;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.File;
import java.security.PrivateKey;
import java.security.PublicKey;

@Data
@Component
@ConfigurationProperties(prefix = "sc.jwt")
public class JwtConfig {
    private String secret; // 秘钥
    private int expire; // 过期时间
    private String pubKeyPath; // 公钥
    private String priKeyPath; // 私钥

    private PublicKey publicKey; // 公钥
    private PrivateKey privateKey; // 私钥

    // 在类被加载时候，就会自动执行该方法
    @PostConstruct
    public void init() {
        try {
            File pubFile = new File(this.pubKeyPath);
            File priFile = new File(this.priKeyPath);

            // 如果公钥或私钥不存在，就自动生成一个
            if (!pubFile.exists() || priFile.exists()) {
                RsaUtils.generateKey(this.pubKeyPath, this.priKeyPath, this.secret);
            }

            // 根据公钥和私钥的路径，生成对应的对象
            this.publicKey = RsaUtils.getPublicKey(this.pubKeyPath);
            this.privateKey = RsaUtils.getPrivateKey(this.priKeyPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
